const AuthService = function ($q, $localStorage, $sessionStorage, HttpService) {
  "ngInject";

  const service = {};
  let currentUser = null;

  // 从localStorage恢复登录状态
  if ($localStorage.currentUser && $localStorage.authToken) {
    currentUser = $localStorage.currentUser;
  }

  service.login = function (username, password) {
    const deferred = $q.defer();

    HttpService.auth
      .login({ username, password })
      .then((response) => {
        if (response.success) {
          currentUser = response.data.user;

          // 保存到localStorage (持久化存储)
          $localStorage.currentUser = currentUser;
          $localStorage.authToken = response.data.token;

          // 同时保存到sessionStorage (会话存储)
          $sessionStorage.currentUser = currentUser;
          $sessionStorage.authToken = response.data.token;

          // 立即可用的原生存储，避免 ngStorage 写入延迟
          try {
            localStorage.setItem("authToken", response.data.token);
            sessionStorage.setItem("authToken", response.data.token);
          } catch (e) {}

          deferred.resolve({
            success: true,
            user: currentUser,
          });
        } else {
          deferred.resolve({
            success: false,
            message: response.message,
          });
        }
      })
      .catch((error) => {
        deferred.resolve({
          success: false,
          message: error.message || "登录失败",
        });
      });

    return deferred.promise;
  };

  service.logout = function () {
    const deferred = $q.defer();

    HttpService.auth
      .logout()
      .then(() => {
        currentUser = null;
        // 清除所有存储
        delete $localStorage.currentUser;
        delete $localStorage.authToken;
        delete $sessionStorage.currentUser;
        delete $sessionStorage.authToken;
        try {
          localStorage.removeItem("authToken");
          sessionStorage.removeItem("authToken");
        } catch (e) {}
        deferred.resolve();
      })
      .catch(() => {
        // 即使后端退出失败，也清除本地数据
        currentUser = null;
        delete $localStorage.currentUser;
        delete $localStorage.authToken;
        delete $sessionStorage.currentUser;
        delete $sessionStorage.authToken;
        try {
          localStorage.removeItem("authToken");
          sessionStorage.removeItem("authToken");
        } catch (e) {}
        deferred.resolve();
      });

    return deferred.promise;
  };

  service.isLoggedIn = function () {
    return (
      currentUser !== null &&
      ($localStorage.authToken || $sessionStorage.authToken)
    );
  };

  service.getCurrentUser = function () {
    return currentUser;
  };

  service.hasRole = function (role) {
    return currentUser && currentUser.role === role;
  };

  service.hasPermission = function (permission) {
    if (!currentUser) return false;

    // 简单的权限检查逻辑
    const permissions = {
      administrator: ["read", "write", "delete", "admin"],
      support: ["read", "write", "support"],
      operator: ["read", "write"],
      user: ["read"],
    };

    const userPermissions = permissions[currentUser.role] || [];
    return userPermissions.includes(permission);
  };

  // 刷新用户信息
  service.refreshUser = function () {
    const deferred = $q.defer();

    if (!service.isLoggedIn()) {
      deferred.reject("用户未登录");
      return deferred.promise;
    }

    HttpService.auth
      .getMe()
      .then((response) => {
        if (response.success) {
          currentUser = response.data;
          $localStorage.currentUser = currentUser;
          $sessionStorage.currentUser = currentUser;
          deferred.resolve(currentUser);
        } else {
          service.logout();
          deferred.reject(response.message);
        }
      })
      .catch((error) => {
        service.logout();
        deferred.reject(error.message || "获取用户信息失败");
      });

    return deferred.promise;
  };

  // 获取认证token
  service.getToken = function () {
    return $localStorage.authToken || $sessionStorage.authToken;
  };

  // 存储用户偏好设置
  service.setUserPreference = function (key, value) {
    if (!$localStorage.userPreferences) {
      $localStorage.userPreferences = {};
    }
    $localStorage.userPreferences[key] = value;
  };

  // 获取用户偏好设置
  service.getUserPreference = function (key, defaultValue) {
    if (
      $localStorage.userPreferences &&
      $localStorage.userPreferences[key] !== undefined
    ) {
      return $localStorage.userPreferences[key];
    }
    return defaultValue;
  };

  // 清除用户偏好设置
  service.clearUserPreferences = function () {
    delete $localStorage.userPreferences;
  };

  // 存储临时会话数据
  service.setSessionData = function (key, value) {
    $sessionStorage[key] = value;
  };

  // 获取临时会话数据
  service.getSessionData = function (key, defaultValue) {
    return $sessionStorage[key] || defaultValue;
  };

  // 清除临时会话数据
  service.clearSessionData = function (key) {
    if (key) {
      delete $sessionStorage[key];
    } else {
      // 清除所有会话数据，但保留用户认证信息
      Object.keys($sessionStorage).forEach(function (sessionKey) {
        if (sessionKey !== "currentUser" && sessionKey !== "authToken") {
          delete $sessionStorage[sessionKey];
        }
      });
    }
  };

  return service;
};

function initAuthService() {
  const angular = window.angular;

  if (!angular) {
    console.error("Angular 未找到，无法初始化认证服务模块");
    return;
  }

  angular
    .module("app.services.auth", ["app.services.http", "ngStorage"])
    .service("AuthService", AuthService);
}

// Listen for vendor libs loaded event
window.addEventListener("vendorLibsLoaded", () => {
  initAuthService();
});

// If Angular already loaded, init directly
if (window.angular) {
  initAuthService();
}
